package com.atguigu.datastructure.search;

/**
 * @author malichun
 * @description
 * @date 2020/3/9 0009 0:36
 * @Version 1.0.0
 */
public class InsertValueSearch {
    public static void main(String[] args) {

        int[] arr = { 1, 8, 10, 89,1000,1000, 1234 };

        int index = insertValueSearch(arr, 0, arr.length - 1, 1234);
        //int index = binarySearch(arr, 0, arr.length, 1);
        System.out.println("index = " + index);

    }

    public static int binarySearch(int[] arr,int left,int right,int findVal){
        System.out.println("二分查找被调用");
        if(left > right){
            return -1;
        }
        int mid=(left+right) /2;
        int midVal=arr[mid];

        if(findVal > midVal){
           return  binarySearch(arr,mid+1, right, findVal);
        }else if(findVal < midVal){
            return binarySearch(arr, left,mid-1, findVal);
        }else{
            return mid;
        }
    }

    //编写插值查找算法
    //说明:插值查找算法,也要求数组是有序的
    /**
     *
     * @param arr 数组
     * @param left 左边索引
     * @param right 右边索引
     * @param findVal 查找值
     * @return 如果找到，就返回对应的下标，如果没有找到，返回-1
     */
    public static int insertValueSearch(int[] arr,int left,int right,int findVal){
        System.out.println("插值查找次数~~");
        if(left>right || findVal < arr[0] || findVal>arr[arr.length-1]){
            return -1;
        }
        //求出mid,自适应
        int mid=left+(right-left) * (findVal - arr[left]) / (arr[right] - arr[left]);
        int midVal = arr[mid];
        if(findVal> midVal){
            return insertValueSearch(arr,mid+1,right,findVal);
        }else if (findVal < midVal) { // 说明向左递归查找
            return insertValueSearch(arr, left, mid - 1, findVal);
        } else {
            return mid;
        }

    }
}
